package api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import domain.User;
import exception.LoginException;
import service.UserService;
import utils.GetRequestJsonUtils;
import utils.Response;
import utils.ResponseCode;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//       1.提取请求中的账号密码
        Response build=null;
        JSONObject object=null;
        User user=null;
        try{//输入参数提取,如果格式错误，则返回异常
            object=GetRequestJsonUtils.getRequestJsonObject(req);
            String userString=object.getString("user");
            System.out.println(userString);
//       2.把账号密码转换成java对象
            user=JSON.parseObject(userString,User.class);
        }catch (Exception e){
            build=Response.build(ResponseCode.ERROR_PARAM);
            resp.setContentType("application/json;charset=utf-8");
            resp.getWriter().write(JSON.toJSON(build).toString());
            return;
        }
//       3.把该对象对应的数据库表中的记录查询出来
        UserService userService=new UserService();
        User userDB =null;
        try {
//      4.判断，如果不存在记录则没有该用户，存在该用户则对照密码，在service里面完成
            userDB = userService.login(user);
//            经过Service返回的一定是成功登录
//       5.账号密码都相同，创建session，往session中添加user属性
//       6.把session的id添加到cookie中，再把cookie添加到消息中
            HttpSession session=req.getSession();
            session.setAttribute("user",userDB);//相当于为该浏览器发放了一个凭证，这个凭证被写在该浏览器在服务器端的session
            Cookie cookie=new Cookie("JSESSIONID",session.getId());//把session的id发给浏览器
            resp.addCookie(cookie);
            String url=null;
            if (userDB.getRole().equals("超级用户")){
                url="/admin/login/home.jsp";
            }else{
                url="/client/myCount.jsp";
            }
            build=Response.build(ResponseCode.SUCCESS_LOGIN,url);
        }catch (LoginException e){
//       把异常消息内容和消息代码添加到ResponseCode中，然后封装成消息
            e.printStackTrace();
            build=Response.build(e.getResponseCode());
        }
//       7.封装消息对象
//       8.转换消息为字符串，返回给浏览器
        System.out.println("aaa");
        resp.setContentType("application/json;charset=utf-8");
        resp.getWriter().write(JSON.toJSON(build).toString());


    }
}
